package com.jwaoo.chat.session.avchat;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.cavan.android.CavanBleDevice;
import com.cavan.android.CavanBleDeviceAdapter;
import com.cavan.android.CavanBleScanner;
import com.dx.as.common.log.LogUtil;
import com.jwaoo.android.JwaooBleToy;
import com.jwaoo.bluetooth.Bluetooth;
import com.jwaoo.chat.ChatHelpter;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static android.content.Context.BLUETOOTH_SERVICE;

/**
 * Created by jwaoo on 2018/1/20.
 */

public class BluetoothHelper {

    private CavanBleDevice currentDevice;
    private CavanBleScanner mBleScanner;
    private CavanBleDeviceAdapter mBleDeviceAdapter;
    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    private String divName;
    private String address;
    private Bluetooth bluetooth;
    private Timer timer;
    private TimerTask timerTask;
    private ListView listView;
    private BluetoothOptionListener listener;
    public BluetoothHelper(BluetoothOptionListener listener) {
        this.listener = listener;
    }


    public void setCurrentDevice(CavanBleDevice currentDevice){
        this.currentDevice = currentDevice;
    }

    public void setListView(ListView listView){
        this.listView = listView;
        mBleDeviceAdapter = new CavanBleDeviceAdapter(listView) {
            @Override
            protected void selectDevice(View view, CavanBleDevice cavanBleDevice) {

            }

            @Override
            public View getView(CavanBleDevice device, View convertView, ViewGroup parent) {
                return listener.getView(this,device,convertView,parent);
            }
        };
        localDevice.clear();
        if (currentDevice != null){
            localDevice.add(currentDevice);
            mBleDeviceAdapter.setDevices(sortDevices(currentDevice), currentDevice);
        }
    }

    public void initBluetooth() {
        bluetooth = Bluetooth.getInstance(ChatHelpter.getContext());
        bluetooth.setOptionCallback(optionCallback);
//        bluetooth.enableSensorDataTranfer(true);
        mBluetoothManager = (BluetoothManager) ChatHelpter.getContext().getSystemService(BLUETOOTH_SERVICE);
        if (Build.VERSION.SDK_INT > 18)
            mBluetoothAdapter = mBluetoothManager.getAdapter();


        mBleScanner = new CavanBleScanner(ChatHelpter.getContext()) {
            @Override
            protected void onScanResult(CavanBleDevice[] devices, CavanBleDevice device) {
                devices = sortDevices(device);
                mBleDeviceAdapter.setDevices(devices, device);
                if (devices != null && devices.length > 0){
                    listener.onScanResult();
                }
            }
            @Override
            protected void onDeviceNotFound() {
                super.onDeviceNotFound();
            }
        };
        mBleScanner.setAutoSelect(5000);
    }

    List<CavanBleDevice> localDevice = new ArrayList<>();

    private CavanBleDevice[] sortDevices(CavanBleDevice device){
        boolean needAdd=false;
        if (localDevice.size() == 0){
            localDevice.add(device);
        }else {
            for (CavanBleDevice value : localDevice) {
                if (value.getName().equals(device.getName())) {
                    needAdd = true;
                }
            }
            if (!needAdd) localDevice.add(device);
        }
        return localDevice.toArray(new CavanBleDevice[localDevice.size()] );
    }

    private void startScan() {
        if (mBleScanner != null) {
            mBleScanner.startScan(null, JwaooBleToy.BT_NAMES);
        }
    }

    public void stopScan() {
        if(mBleScanner!=null)
            mBleScanner.stopScan();
    }

    public void startSearch(){
        if (mBleScanner.isAdapterEnabled()) {
            startScan();
        } else {

        }
    }

    public void doBluetoothOption(int mode,int level,boolean isSpeedByFreq){
        try {
            bluetooth.setMotorWorkMode(mode);
            if (isSpeedByFreq) {
                bluetooth.setMotorWorkSpeedByFreq(level);
            }else {
                bluetooth.setMotorWorkSpeed(level);
            }

        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    public void initTimer(){
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                int sp = bluetooth.getMotionFreq();
//                bluetooth.setMotorWorkSpeedByFreq(sp);
                listener.onOptionSpeed(sp);
                LogUtil.d("Bluetooth",sp+"");
            }
        };
    }

    public void startTimer(){
        timer.schedule(timerTask,1000,1000);
    }

    public void stopTimer(){
        try {
            timerTask.cancel();
            timer.cancel();
        }catch (Exception ex){
            ex.printStackTrace();
        }

    }

    public void doBluetoothConnect(String address){
        this.address = address;
        bluetooth.connect(address);
    }

    public void doBluetoothDisConnect(){
        currentDevice = null;
        this.address = "";
        bluetooth.disconnect();
    }

    interface BluetoothOptionListener{
        View getView(final CavanBleDeviceAdapter adapter, final CavanBleDevice device, View convertView, ViewGroup parent);
        void onScanResult();
        void onOptionSpeed(int speed);
        void onConnectionStateChanged(boolean connected);
    }

    private Bluetooth.OptionCallback optionCallback = new Bluetooth.OptionCallback() {
        @Override
        public void onConnectionStateChanged(boolean connected) {
            listener.onConnectionStateChanged(connected);
            if (!connected) {
                bluetooth.connect(address);
                mBleDeviceAdapter.notifyDataSetChanged();
                currentDevice = null;
            }
        }
    };


}
